import {
  Component,
  Input,
  Output,
  EventEmitter,
  OnInit,
  OnChanges
} from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { HttpServcie } from "../../../../service/http.service";
import { ElevatorInfoBean } from "../bean/elevatorInfo.bean";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { Router, ActivatedRoute } from "@angular/router";
import * as moment from "moment";
import { FileUploader, FileItem, ParsedResponseHeaders } from "ng2-file-upload";
import { Config } from "../../../../service/config";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
@Component({
  selector: "elevator-maintenance",
  templateUrl: "elevator-maintenance.html",
  styleUrls: ["elevator-maintenance.scss"]
})
/**
 * 电梯详细页面
 */
export class ElevatotMaintenancePage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  inDate: any = {};
  elevatorTypeName: string;
  usedPartyName: string;
  maintenancePartyName: string;
  branchOfficeName: string;
  maintenanceUserFirstName: string;
  maintenanceUserSecondName: string;
  examinationUserFirstName: string;
  examinationUserSecondName: string;
  safeUserName: string;
  picList: any = [];
  @Output("outPut") outPut = new EventEmitter();
  @Input("inValue") inValue: any;
  //电梯信息
  elevatorlnfoBean: ElevatorInfoBean = new ElevatorInfoBean();

  //电梯添加的权限(功能)
  funList: any = [];

  //机构的集合
  partyList: any = [];
  //省市区
  options: any = [];
  //地址
  addresOptions: any = [];
  //电梯类型
  elevatorTypeOptions: any = [];
  //物业
  wuyeList: any = [];
  //维保
  weibaoList: any = [];
  // 监管
  jianguanList: any = [];
  //安全管理人员
  anquanList: any = [];
  //维保人员
  weibaoren: any = [];
  // 检验人员
  jianyanren: any = [];
  showImage: any = [];
  config: any = Config;
  currentModal: NzModalSubject;
  elevatorId : string;

  elevatorAddress:string="";


  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private modalService: NzModalService
  ) {
    let partyTypeId = JSON.parse(window.localStorage.getItem("user")).partyType;
    let parentId = "";
    if (partyTypeId == "4") {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyId;
    } else {
      parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
    }
    //修改获取电梯详情为调查询接口
    this.activatedRoute.params.subscribe(data => {
      if(data.elevatorId !=null && data.elevatorId !=undefined){
        this.elevatorId = data.elevatorId;
        this.httpServcie.queryElevatorById(this.elevatorId).subscribe(data =>{
          this.elevatorlnfoBean = data.data;
          // 拼接地址
          if (this.elevatorlnfoBean.elevatorStreet != null && this.elevatorlnfoBean.elevatorStreet != '' && this.elevatorlnfoBean.elevatorStreet != "NULL") {
            this.elevatorAddress += this.elevatorlnfoBean.elevatorStreet
          }
          if (this.elevatorlnfoBean.elevatorAddr != null && this.elevatorlnfoBean.elevatorAddr != '' && this.elevatorlnfoBean.elevatorAddr != "NULL") {
            this.elevatorAddress += this.elevatorlnfoBean.elevatorAddr
          }
          if (this.elevatorlnfoBean.buildAddr != null && this.elevatorlnfoBean.buildAddr != '' && this.elevatorlnfoBean.buildAddr != "NULL") {
            this.elevatorAddress += this.elevatorlnfoBean.buildAddr
          }

          this.getElevatorData(parentId);
        });
      }else{
        // 当电梯分布图进来时
        this.inDate = Object.assign({}, data);
        this.elevatorlnfoBean = this.inDate;
      }
    });
  }

  /**
   * 对电梯详情的数据对象展示处理
   */
  getElevatorData(parentId){
    this.elevatorlnfoBean.nextCheckDateShow = new Date(
      moment(this.elevatorlnfoBean.nextCheckDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.lastMaintenanceTimeShow = new Date(
      moment(this.elevatorlnfoBean.lastMaintenanceTime).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.insuranceDateShow = new Date(
      moment(this.elevatorlnfoBean.insuranceDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextHalfmonMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextHalfmonMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextQuarterlyMainteDateShow = new Date(
      moment(this.elevatorlnfoBean.nextQuarterlyMainteDate).format(
        "YYYY-MM-DD"
      )
    );
    this.elevatorlnfoBean.nextHalfyearMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextHalfyearMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextYearMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextYearMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.beUsedDateShow = new Date(
      moment(this.elevatorlnfoBean.beUsedDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.governorCkDateShow = new Date(
      moment(this.elevatorlnfoBean.governorCkDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.lastInspectDateShow = new Date(
      moment(this.elevatorlnfoBean.lastInspectDate).format("YYYY-MM-DD")
    );
    //查询需要的数据
    Observable.forkJoin(
      //查询电梯类型
      this.httpServcie.queryelevatorTypeList(),
      //查询当前用户所属机构下的物业机构
      this.httpServcie.queryByIdAndTypeList({ partyType: 2 }),
      //查询当前用户所属机构下的维保
      this.httpServcie.queryByIdAndTypeList({ partyType: 1 ,id: parentId}),
      //查询监管机构
      this.httpServcie.queryByIdAndTypeList({ partyType: 4 }),
    ).subscribe(data => {

      if (data[0].status == 200) {
        //机构类型
        this.elevatorTypeOptions = data[0].data.list;
        this.elevatorTypeOptions.forEach(element => {
          if (this.elevatorlnfoBean.elevatorTypeId == element.id) {
            this.elevatorTypeName = element.typeName;
          }
        });
      }
      if (data[1].status == 200) {
        //物业机构
        this.wuyeList = data[1].data;
        this.wuyeList.forEach(element => {
          if (this.elevatorlnfoBean.usedPartyId == element.id) {
            this.usedPartyName = element.partyName;
          }
        });
      }
      if (data[2].status == 200) {
        //维保机构
        this.weibaoList = data[2].data;
        this.weibaoList.forEach(element => {
          if (this.elevatorlnfoBean.maintenancePartyId == element.id) {
            this.maintenancePartyName = element.partyName;
          }
        });
      }
      if (data[3].status == 200) {
        //监管机构
        this.jianguanList = data[3].data;
        this.jianguanList.forEach(element => {
          if (this.elevatorlnfoBean.branchOffice == element.id) {
            this.branchOfficeName = element.partyName;
          }
        });
      }

      //省市区
      let cityList: any = [];
      Config.CITY.forEach(element => {
        if (this.elevatorlnfoBean.elevatorProvince == element.value) {
          cityList.push(element);
        }
        if (this.elevatorlnfoBean.elevatorCity == element.value) {
          cityList.push(element);
        }
        if (this.elevatorlnfoBean.elevatorArea == element.value) {
          cityList.push(element);
        }
      });
      this.addresOptions = cityList;

      //维保人员
      if (
        undefined != this.elevatorlnfoBean.maintenancePartyId &&
        null != this.elevatorlnfoBean.maintenancePartyId
      ) {
        this.httpServcie
          .queryUserByPartyId(this.elevatorlnfoBean.maintenancePartyId)
          .subscribe(data => {
            if (data.status == 200) {
              this.weibaoren = data.data;
              this.weibaoren.forEach(element => {
                if (this.elevatorlnfoBean.maintenanceUserFirst == element.id) {
                  this.maintenanceUserFirstName = element.userName;
                }
                if (this.elevatorlnfoBean.maintenanceUserSecond == element.id) {
                  this.maintenanceUserSecondName = element.userName;
                }
              });
            }
          });
      }

      //安全管理员
      if (
        undefined != this.elevatorlnfoBean.usedPartyId &&
        null != this.elevatorlnfoBean.usedPartyId
      ) {
        this.httpServcie
          .queryUserByPartyId(this.elevatorlnfoBean.usedPartyId)
          .subscribe(data => {
            if (data.status == 200) {
              this.anquanList = data.data;
              this.anquanList.forEach(element => {
                if (this.elevatorlnfoBean.safeUserId == element.id) {
                  this.safeUserName = element.userName;
                }
              });
            }
          });
      }

      // 检验人员
      if (
        undefined != this.elevatorlnfoBean.examinationPartyId &&
        null != this.elevatorlnfoBean.examinationPartyId
      ) {
        this.httpServcie
          .queryUserByPartyId(this.elevatorlnfoBean.examinationPartyId)
          .subscribe(data => {
            if (data.status == 200) {
              this.jianyanren = data.data;
              this.jianyanren.forEach(element => {
                if (this.elevatorlnfoBean.examinationUserFirst == element.id) {
                  this.examinationUserFirstName = element.userName;
                }
                if (this.elevatorlnfoBean.examinationUserSecond == element.id) {
                  this.examinationUserSecondName = element.userName;
                }
              });
            }
          });
      }

      //反显图片
      if (this.elevatorlnfoBean.elevatorPhotoUrl) {
        this.showImage = this.elevatorlnfoBean.elevatorPhotoUrl.split(",");
      }
    });
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      elevatorNum: [null, [Validators.required]],
      serialNum: [null, [Validators.required]],
      elevatorProvince: [null, [Validators.required]],
      elevatorArea: [null, [Validators.required]],
      addresOptions: [null, [Validators.required]],
      elevatorStreet: [null, [Validators.required]],
      elevatorAddr: [null, [Validators.required]],
      elevatorModel: [null, [Validators.required]],
      elevatorTypeId: [null, [Validators.required]],
      elevatorPhotoUrl: [null, [Validators.required]],
      registrationCode: [null, [Validators.required]],
      maintenancePartyId: [
        this.elevatorlnfoBean.maintenancePartyId,
        [Validators.required]
      ],
      usedPartyId: [this.elevatorlnfoBean.usedPartyId, [Validators.required]],
      buildingInfo: [null, [Validators.required]],
      elevatorBuildingNum: [null, [Validators.required]],
      createCompanyName: [null, [Validators.required]],
      examinationPartyName: [null, [Validators.required]],
      nextCheckDateShow: [null, [Validators.required]],
      safeUserId: [this.elevatorlnfoBean.safeUserId, [Validators.required]],
      maintenanceUserFirst: [
        this.elevatorlnfoBean.maintenanceUserFirst,
        [Validators.required]
      ],
      maintenanceUserSecond: [
        this.elevatorlnfoBean.maintenanceUserSecond,
        [Validators.required]
      ],
      rescuePhoneNum: [null, [Validators.required]],
      insuranceNum: [null, [Validators.required]],
      lastMaintenanceTimeShow: [null, [Validators.required]],
      isStop: [null, [Validators.required]],
      nextMaintenanceDateShow: [null, [Validators.required]],
      pointsNum: [null, [Validators.required]],
      qrCodeUrl: [null, [Validators.required]],
      elevatorTypeName: [null, [Validators.required]],
      usedPartyName: [null, [Validators.required]],
      safeUserName: [null, [Validators.required]],
      maintenancePartyName: [null, [Validators.required]],
      maintenanceUserFirstName: [
        this.elevatorlnfoBean.maintenanceUserFirst,
        [Validators.required]
      ],
      maintenanceUserSecondName: [
        this.elevatorlnfoBean.maintenanceUserSecond,
        [Validators.required]
      ],
      insuranceName: [null, [Validators.nullValidator]],
      insuranceDateShow: [null, [Validators.nullValidator]],
      maintTel: [null, [Validators.nullValidator]],
      nextHalfmonMaintDateShow: [null, [Validators.nullValidator]],
      nextQuarterlyMainteDateShow: [null, [Validators.nullValidator]],
      nextHalfyearMaintDateShow: [null, [Validators.nullValidator]],
      nextYearMaintDateShow: [null, [Validators.nullValidator]],
      outsideNum: [null, [Validators.nullValidator]],
      url: [null, [Validators.nullValidator]],
      buildAddr: [null, [Validators.nullValidator]],
      usedNum: [null, [Validators.nullValidator]],
      beUsedDateShow: [null, [Validators.nullValidator]],
      governorCkDateShow: [null, [Validators.nullValidator]],
      floorStation: [null, [Validators.nullValidator]],
      safeUserTel: [null, [Validators.nullValidator]],
      buildPartyName: [null, [Validators.nullValidator]],
      ratedLoad: [null, [Validators.nullValidator]],
      runSpeed: [null, [Validators.nullValidator]],
      angle: [null, [Validators.nullValidator]],
      stepWidth: [null, [Validators.nullValidator]],
      liftHeight: [null, [Validators.nullValidator]],
      driveWay: [null, [Validators.nullValidator]],
      brandName: [null, [Validators.nullValidator]],
      examinationUserFirst: [
        this.elevatorlnfoBean.examinationUserFirst,
        [Validators.required]
      ],
      examinationUserSecond: [
        this.elevatorlnfoBean.examinationUserSecond,
        [Validators.required]
      ],
      examinationUserFirstName: [
        this.elevatorlnfoBean.examinationUserFirst,
        [Validators.required]
      ],
      examinationUserSecondName: [
        this.elevatorlnfoBean.examinationUserSecond,
        [Validators.required]
      ],
      lastInspectDateShow: [null, [Validators.nullValidator]],
      innerId: [null, [Validators.nullValidator]],
      programName: [null, [Validators.required]],
      branchOffice: [this.elevatorlnfoBean.branchOffice, [Validators.required]],
      branchOfficeName: [null, [Validators.required]],
      elevatorPlace: [null, [Validators.required]]
    });
  }

  ngOnChanges() {
    this.activatedRoute.params.subscribe(data => {
      //深度 clone 一下，否则不能修改
      this.inDate = Object.assign({}, data);
    });
    if (this.inValue) {
      this.elevatorlnfoBean = this.inValue;
    } else {
      this.elevatorlnfoBean = this.inDate;
    }
    this.elevatorlnfoBean.nextCheckDateShow = new Date(
      moment(this.elevatorlnfoBean.nextCheckDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.lastMaintenanceTimeShow = new Date(
      moment(this.elevatorlnfoBean.lastMaintenanceTime).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.insuranceDateShow = new Date(
      moment(this.elevatorlnfoBean.insuranceDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextHalfmonMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextHalfmonMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextQuarterlyMainteDateShow = new Date(
      moment(this.elevatorlnfoBean.nextQuarterlyMainteDate).format(
        "YYYY-MM-DD"
      )
    );
    this.elevatorlnfoBean.nextHalfyearMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextHalfyearMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.nextYearMaintDateShow = new Date(
      moment(this.elevatorlnfoBean.nextYearMaintDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.beUsedDateShow = new Date(
      moment(this.elevatorlnfoBean.beUsedDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.governorCkDateShow = new Date(
      moment(this.elevatorlnfoBean.governorCkDate).format("YYYY-MM-DD")
    );
    this.elevatorlnfoBean.lastInspectDateShow = new Date(
      moment(this.elevatorlnfoBean.lastInspectDate).format("YYYY-MM-DD")
    );
  }

  submitForm() { }

  //交验
  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  executeArray(items, res: any) {
    items.map(item => {
      if (item.checked) {
        res.push({ name: item.text, id: item.value });
      }
      if (item.childList) {
        this.executeArray(item.childList, res);
      }
    });

    return res;
  }

  collapse(array, data, $event) {
    if ($event === false) {
      if (data.childList) {
        data.childList.forEach(d => {
          const target = array.find(a => a.authorId === d.authorId);
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root) {
    const stack = [],
      array = [],
      hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.childList) {
        for (let i = node.childList.length - 1; i >= 0; i--) {
          stack.push({
            ...node.childList[i],
            level: node.level + 1,
            expand: false,
            parent: node
          });
        }
      }
    }

    return array;
  }

  visitNode(node, hashMap, array) {
    if (!hashMap[node.authorId]) {
      hashMap[node.authorId] = true;
      array.push(node);
    }
  }
  toMaintenance(id, typeId) {
    this.router.navigate([
      "/home/maintenace-list",
      { id: id, elevatorTypeId: typeId }
    ]);
  }
  //一梯一档跳转
  toOnelevator() {
    this.router.navigate([
      "/home/onelevator-info",
      {
        elevatorNum: this.elevatorlnfoBean.elevatorNum,
        elevatorId: this.elevatorlnfoBean.id
      }
    ]);
  }
  //维修记录跳转
  tomaintain(elevatorId) {
    this.router.navigate([
      "/home/maintenance-record",
      {
        elevatorId: elevatorId
      }
    ]);
  }
  //巡检记录查询（物业）跳转
  toinspection(elevatorId) {
    this.router.navigate([
      "/home/inspection-record",
      {
        elevatorId: elevatorId,
        elevatorType: this.elevatorlnfoBean.elevatorTypeId
      }
    ]);
  }

  toSelfCheck(elevatorId) {
    this.router.navigate([
      "/home/self-check",
      {
        elevatorId: elevatorId,
        elevatorType: this.elevatorlnfoBean.elevatorTypeId
      }
    ]);
  }
  //应急救援记录 跳转
  torescue(elevatorId) {
    this.router.navigate([
      "/home/elevator-rescue",
      {
        elevatorId: elevatorId
      }
    ]);
  }

  toBack() {
    if (this.inValue) {
      this.outPut.emit();
    } else {
      window.history.back();
    }

    // this.router.navigate
  }
  toappraisal(elevatorId) {
    this.router.navigate([
      "/home/elevator-appraisal",
      { elevatorId: elevatorId }
    ]);
  }

  //选择物业信息
  wuyeChange() {
    this.elevatorlnfoBean.safeUserId = null;
    this.anquanList = [];
    if (
      undefined != this.elevatorlnfoBean.usedPartyId &&
      null != this.elevatorlnfoBean.usedPartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorlnfoBean.usedPartyId)
        .subscribe(data => {
          if (data.status == 200) {
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "5") {
                  this.anquanList.push(user);
                }
              });
            }
          }
        });
    }
  }

  //选择维保
  weibaoChange() {
    this.weibaoren = [];
    this.elevatorlnfoBean.maintenanceUserFirst = null;
    this.elevatorlnfoBean.maintenanceUserSecond = null;
    if (
      undefined != this.elevatorlnfoBean.maintenancePartyId &&
      null != this.elevatorlnfoBean.maintenancePartyId
    ) {
      this.httpServcie
        .queryUserByPartyId(this.elevatorlnfoBean.maintenancePartyId)
        .subscribe(data => {
          if (data.status == 200) {
            if (data.data && data.data.length > 0) {
              data.data.forEach(user => {
                if (user.type == "user" && user.roleId == "7") {
                  this.weibaoren.push(user);
                }
              });
            }
          }
        });
    }
  }

  showLargeImage(titlepic, contentpic, footerpic, img) {
    this.picList = [];
    this.picList.push(img);
    this.currentModal = this.modalService.open({
      title: titlepic,
      content: contentpic,
      footer: footerpic,
      maskClosable: false,
      width: 800,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }
}
